package com.jycgame.dollmachine;

import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unity3d.player.*;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.os.Message;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import java.util.Map;

import com.alipay.sdk.app.PayTask;
import com.unity3d.player.UnityPlayerActivity;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;

public class DollMachineActivity extends UnityPlayerActivity
{
    //支付宝
    public static final String APPID = "2018042460073110";

    //微信
    private IWXAPI api;

    protected  void onCreate(Bundle savedInstanceState) {
        //微信需要初始化
        api = WXAPIFactory.createWXAPI(this, "wxffdcd4fcc759ef72");

        super.onCreate(savedInstanceState);

        Log.i("Unity", "DollMachineEn");
    }

    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            Log.i("Unity", "Get alipay result message: " + msg.what);
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    Log.i("Unity", "Get alipay result status: " + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        UnityPlayer.UnitySendMessage("LowLevelMessageCenter", "AliPayCallback", resultStatus);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Log.i("Unity", "Try to send message to user: " + resultStatus);
                        UnityPlayer.UnitySendMessage("LowLevelMessageCenter", "AliPayCallback", resultStatus);
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    /**
     * 支付宝支付业务
     *
     * @param
     */
    public void AlipayV2() {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = true;
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = "MIIEowIBAAKCAQEAwoqm+4Zc9XoosRvmjRmw8R///cIblI2vmIrsXfcdVWN0l5Kkm5cPNrQBAuMDC7OhLj3SRxXdLwj3UiBdxa5GCNWSNMQbJX8PhRkxkqjbA7m0BHfP28hYCUrqtf7n+yZQAs7CFlwWodkQBllOXyKfxdavUV8jCULF5Oh6LMlQdIFBNlR965GbLWidPN+TznUK6dIp2URXIr4b3Kr6sAa+g6XHHy5xWG5DLaDF3RVmxUOXcQVrPZSoXJViTi4tsYUjsI9LCN13LXUBmYWiob53TOc/k0hfg7q/LuJJM07c4EHtvFyXTuX9TQLk8WEx5wizUjsE3PHLiwef1D1qNohdhQIDAQABAoIBAEMkjYtEDXNfzQmLgp/yXQJrs/OF+fTkjdVNJVUtA7/DyqrBnvRgR4zuxWaUqSlxvtBx39BO+H7STmHW7+ZZRqyn4YU6pc/kMZwTXOusQaLghgQAwgmt9MyIQce8iZ5B092UNKJ4+Aq2GvTF/+mPzqr+dJXWCwaYOCrQHdK1TIJYu2P20xB1QJzVFktOE1l4CW9SaoqQwWO9RJtIJ07UtsWz6s+/uDEx6XAnOe/OjL4NbkFmZdBOCa6NYJ0xU0ixIT+KtJxQt9uH2TMEDkidng0ntkEEWz+dPTe7dxdQOt0ULee5Fh623kHV33ow7v3PZoVmwG1OTu16hTgKiOedQyECgYEA82MTfpyaYQTu8/JUQdnaEmEFSwgObhP8ccfkz0t0ZCHbm6QQsDgenxN/emVD6URD4Wv0OKU+1TCrH4O0vVaf27IVB+slmlkuHl7L81sD/uMvfziEamMhPPRJ5YFRvJM6Hb2jG4gX8k2Tmw5cQ1qTZM7UujENgKoQMgTHVgGdBP0CgYEAzJ+QAeLAZBzYBHD24NOkqPoGw1lOIZirUaL/bnaIcWupl099r4zqqq1SyXs7F26d2lF6dpLngmCn6dNcEEEhoQksbVfPMr2fK6G0RXUcP+e5DF5nJciNUjrb8rYDqnpV7c65sGJwDEeyuoK7qzuKwBomssAY5UHx12CpX1JyJSkCgYA+vWWDF9977weh/u/VYdEjN7tjkhoWKjTDJ+JFxY+lWE0CHBLpOi46l44fAQe2lBBjha6ZA4/k6PzTzOHEhRYETi25stYoqaCH16v/eZDYHbxasTkBK7ifu+FotiNZ1yH+FKp9KGHz5ieMqvEBs9GXBPI1ZPu0FSLDohO4igXuCQKBgETOHqlTque+/zA3H/ynjgW31RBY9jm70VepHITzXJvu3N7hPt0J4Fq131Gam1scuf2QSkKW0Tv47l1k0d8xV3KD2CmITka8lkognLKCV5Zxf7rV/48n6cVNv2nUpFTtv/kv+yaBYzXt4f5vOVWxts0zvfF7QKPOUdjfSvSfj3xJAoGBAJ4s9Qz4afMFd7ofac7Z14jZA7li0TcIQoEF9gz57FZGT5n88QKpKtaEgiS1Lva+PRFsMwvKaFTs7foNQONWyfjThPDtWfj1ZewEL+UdZKxbFjTTvflBdwE2R7hY7R4vchcpsmKzG/A2DG8LjUqV775/a5xeAyJ8lI6EnOouoDuN";
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(DollMachineActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 微信支付业务
     *
     * @param v
     */
    private static final int PAY_SUPPORTED_SDK_INT = 570425345;
    public boolean IsWeChatInstalled() {
        return api.isWXAppInstalled();
    }

    public boolean IsWeChatSupportAPI() {
        return api.getWXAppSupportAPI() >= PAY_SUPPORTED_SDK_INT;
    }

    public void WeChatPay(String appid, String partnerId, String prepayId, String nonceStr, String timeStamp, String packageValue, String sign) {

        boolean isWeChatInstalled = api.isWXAppInstalled();
        Log.i("Unity", "AAR包支撑功能");
        Log.i("Unity", "WeChat installed: " + isWeChatInstalled);

        if (isWeChatInstalled == false) return;

        PayReq req = new PayReq();

        req.appId = appid;
        req.partnerId = partnerId;
        req.prepayId = prepayId;
        req.nonceStr = nonceStr;
        req.timeStamp = timeStamp;
        req.packageValue = packageValue;
        req.sign = sign;

        Log.i("Unity", req.appId);
        Log.i("Unity", req.partnerId);
        Log.i("Unity", req.prepayId);
        Log.i("Unity", req.nonceStr);
        Log.i("Unity", req.timeStamp);
        Log.i("Unity", req.packageValue);
        Log.i("Unity", req.sign);

        boolean result = api.sendReq(req);
        Log.i("Unity", "WeChatPay called." + result);
    }

    public void Test(String msg) {
        Log.i("Unity", "I see you with wxapi!");
    }
}
